<template>
  <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="table-list min-fill-page">
    <div v-if="!showMobilePage" class="filter">
      <div class="flex">
        <el-button :loading="clearLoading" size="small" type="primary" @click="handleBatchClear">批量清理</el-button>
      </div>
    </div>
    <div v-loading="loading" style="min-height: 100px;">
      <el-table
        v-el-table-infinite-scroll="loadMore"
        v-if="list.items && list.items.length"
        ref="feishuTodoTableRef"
        :data="list.items"
        :row-height="rowHeight()"
        :height="setTableHeight"
        class="fb-table todo-table"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        header-cell-class-name="order-data-header-cell"
        hightlight-current-row
        @select="selectTable"
        @select-all="selectTable">
        <el-table-column
          align="center"
          type="selection"
          width="50"/>
        <el-table-column align="left" label="审批类型" min-width="150">
          <template slot-scope="scope">
            <div class="flex">
              <div :style="{ background: scope.row.icon && JSON.parse(scope.row.icon).iconColor ? JSON.parse(scope.row.icon).iconColor : defaultColor }" class="module-icon">
                <img :src="getIcon(scope.row.icon ? JSON.parse(scope.row.icon).icon : '')">
              </div>
              <ToolTip :content="scope.row.name" style="flex: 1;min-width: 0;" />
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="审批单号" min-width="160">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.approvalNo" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="发起时间" min-width="180">
          <template slot-scope="scope">
            <ToolTip :content="format(scope.row.createTime,'YYYY/MM/DD HH:mm:ss')" />
          </template>
        </el-table-column>
        <el-table-column align="left" label="发起人" min-width="120">
          <template slot-scope="scope">
            <div class="column-creator">
              <img :src="scope.row.avatar || avatarPng" alt="发起人">
              <span>{{ scope.row.proposerName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="链接" min-width="100">
          <template slot-scope="scope">
            <el-tooltip
              :open-delay="800"
              class="item"
              placement="top"
              effect="dark">
              <div slot="content" style="max-width: 200px;">{{ getDetailLink(scope.row) }}</div>
              <div class="link-row" @click="toDetailPage(scope.row)">
                <div>点击跳转</div>
                <div><img :src="linkPng" alt="link"></div>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column :fixed="showMobilePage ? 'right' : false" align="left" label="操作" width="60">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleClear(scope.row.clearId)">清理</el-button>
          </template>
        </el-table-column>
        <p v-if="list.items.length > 6" slot="append" class="load-more">
          {{ hasMore ? '向下滚动加载更多↓' : '没有更多数据了~' }}
        </p>
      </el-table>
      <EmptyPlaceholder v-else style="margin-bottom: 24px" />
    </div>
    <fixed-pagination v-if="list.count > 0 && !showMobilePage || showMobilePage">
      <template v-if="showMobilePage">
        <div style="display: flex;justify-content: center;width: 100%;">
          <el-button :loading="clearLoading" size="small" type="primary" @click="handleBatchClear">批量清理</el-button>
        </div>
      </template>
      <template v-else>
        <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
      </template>
    </fixed-pagination>
  </div>
</template>

<script>
// components
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
// api
import { getFeishuTodoList, clearFeishuTodo } from '@/api/todo';
// tools
import { mapState } from 'vuex';
import { format } from '@/filters/date';
import { debounce } from '@/utils';
import axios from 'axios';
// mixins
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import todo from '@/mixins/todo';
import iconConfig from '@/mixins/iconConfig';
// img
import avatarPng from '@/assets/todo/avatar.png';
import linkPng from '@/assets/medium/publish-link.png';
export default {
  components: { EmptyPlaceholder },
  mixins: [tableSelections, TableAdaptive, mobileTable, todo, iconConfig],
  data() {
    return {
      avatarPng,
      linkPng,
      newTabOpen: true,
      list: {
        items: [],
        count: 0,
        pageToken: null // 服务端返回的token，请求下一页的入参需要用到
      },
      loading: false,
      tableRefName: 'feishuTodoTableRef', // 表格的ref名称
      idKey: 'processId', // 唯一表示字段
      clearLoading: false,
      cancelToken: null,
      perPage: 10,
      hasMore: true
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  created() {
    this.fetchData();
  },
  methods: {
    format,
    handleBatchClear: debounce(function() {
      if (!this.multipleSelectionAll.length) {
        this.$message.warning('请勾选要清理的飞书待办');
        return;
      }
      const ids = this.multipleSelectionAll.map(it => it.clearId).join(',');
      this.clearFeishuTodo(ids, '请确认是否在飞书清理所选中的待办?');
    }, 500),
    handleClear(id) {
      this.clearFeishuTodo(String(id), '请确认是否在飞书清理该待办?');
    },
    clearFeishuTodo(ids, text) {
      this.$confirm(text, {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        this.clearLoading = true;
        clearFeishuTodo({ ids }).then(res => {
          if (res.code === 200) {
            this.$message.success(res.message);
            this.clearLoading = false;
            this.list.pageToken = null;
            this.hasMore = true;
            this.multipleSelectionAll = [];
            this.$nextTick(() => {
              this.fetchData();
            });
          }
        }).catch(err => {
          this.clearLoading = false;
          console.error(err.message);
        });
      }).catch(() => {
        return;
      });
    },
    formatParams() {
      const params = {
        perPage: this.perPage
      };
      if (this.list.pageToken) {
        params.pageToken = this.list.pageToken;
      }
      return params;
    },
    async fetchData(concat = false) {
      this.loading = true;
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();
      this.listCancelToken = source;
      const params = this.formatParams();
      try {
        const res = await getFeishuTodoList(params, source.token);
        res.data.items = concat ? (res.data.items ? this.list.items.concat(res.data.items) : this.list.items) : res.data.items;
        this.list = res.data || { items: [] };
        this.hasMore = res.data.hasMore;
        this.loading = false;
      } catch (err) {
        console.error(err.message);
      }
    },
    loadMore() {
      if (this.list.items) {
        if (this.hasMore && !this.loading) {
          this.fetchData(true);
        }
      }
    },
    toDetailPage(row) {
      const url = this.getDetailLink(row);
      window.open(url, '_blank');
    }
  }
};
</script>

<style lang="scss" scoped>
%flex {
  display: flex;
  align-items: center;
}
.table-list {
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding: 20px 20px 55px 20px;
}
.column-creator {
  display: flex;
  align-items: center;
  img {
    width: 32px;
    height: 32px;
    border-radius: 100%;
  }
  span {
    margin-left: 8px;
  }
}
.filter {
  @extend %flex;
  margin-bottom: 16px;
  justify-content: flex-end;
}
.link-row {
  display: flex;
  align-items:center;
  color: #406eff;
  cursor: pointer;
  img {
    width: 11px;
    height: 100%;
    margin-left: 3px;
  }
  .el-icon-link {
    font-size: 12px;
  }
}
.todo-table {
  .load-more {
    display: flex;
    justify-content: center;
    margin: 0;
    padding: 4px 0;
    background-color: #F5F5F5;
    color: #999;
    font-weight: normal;
  }
  .flex {
    display: flex;
    align-items: center;
    .module-icon {
      width: 24px;
      height: 24px;
      margin-right: 4px;
      background-color: transparent;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 6px;
      > img {
        width: 14px;
        height: 14px;
      }
    }
  }
}
</style>
